from selenium import webdriver
from selenium.common import TimeoutException
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
import time
from bs4 import BeautifulSoup

# 配置Selenium
chrome_options = Options()
chrome_options.add_argument("--headless")  # 无头模式
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36")
chrome_options.add_argument("--blink-settings=imagesEnabled=false")
chrome_options.add_experimental_option("prefs", {
    "profile.managed_default_content_settings.images": 2,
    "profile.managed_default_content_settings.javascript": 1,  # 保留JS（动态内容可能需要）
})

# 指定Chrome驱动路径
service = Service('./chromedriver.exe')  # 替换为你的chromedriver路径

driver = webdriver.Chrome(service=service, options=chrome_options)
driver.set_page_load_timeout(10)


def get_prince_easymoney(url):
    # page_source = None
    try:
        driver.get(url)
        page_source = driver.page_source
    except TimeoutException:
        print("页面加载超时，尝试继续获取源码")
        page_source = driver.page_source
    soup = BeautifulSoup(page_source, 'html.parser')

    zxj_div = soup.find('div', class_='zxj')
    price_span = zxj_div.find('span').find('span') if zxj_div else None

    # 提取价格文本
    if price_span:
        price = float(price_span.get_text(strip=True))
        return price
    else:
        return 0.00


def get_prince_sina(url):
    driver.get(url)
    page_source = driver.page_source
    soup = BeautifulSoup(page_source, 'html.parser')
    price_span = soup.find('span', class_='price')

    if price_span:
        # 获取文本内容并转换为浮点数
        price = float(price_span.text)
        return price
        # print(price)  # 输出: 1311.0
        # # 如果需要保留两位小数
        # print("{:.2f}".format(price))  # 输出: 1311.00
    else:
        return 0.00


def get_prince_baidu(url):
    # page_source = None
    try:
        driver.get(url)
        page_source = driver.page_source
    except TimeoutException:
        print("页面加载超时，尝试继续获取源码")
        page_source = driver.page_source
    soup = BeautifulSoup(page_source, 'html.parser')
    price_span = soup.find('span', class_='b_price')

    if price_span:
        # 获取文本内容并转换为浮点数
        price = float(price_span.text)
        return price
        # print(price)  # 输出: 1311.0
        # # 如果需要保留两位小数
        # print("{:.2f}".format(price))  # 输出: 1311.00
    else:
        return 0.00


def get_data_easymoney(pre, time_, uid):
    pre_time = pre + time_
    url_ = "https://quote.eastmoney.com/qihuo/" + pre_time + ".html"
    print(url_)
    price = get_prince_easymoney(url_)
    # 打开文件（如果不存在会自动创建），以追加模式写入文本
    with open('example.txt', 'a', encoding='utf-8') as file:
        file.write(f"""{pre}_{uid} {time_} {pre_time} {price}\n""")  # 注意手动添加换行符
    print(pre, time_, pre_time, price)


def get_data_sina(pre, time_, uid):
    pre_time = pre + time_

    price = get_prince_sina("https://finance.sina.com.cn/futures/quotes/" + pre_time + ".shtml")
    # 打开文件（如果不存在会自动创建），以追加模式写入文本
    with open('example.txt', 'a', encoding='utf-8') as file:
        file.write(f"""{pre}_{uid} {time_} {pre_time} {price}\n""")  # 注意手动添加换行符
    print(pre, time_, pre_time, price)


def get_data_baidu(pre, time_, uid):
    pre_time = pre + time_

    price = get_prince_baidu("https://gushitong.baidu.com/futures/ab-" + pre_time)
    # 打开文件（如果不存在会自动创建），以追加模式写入文本
    with open('example.txt', 'a', encoding='utf-8') as file:
        file.write(f"""{pre}_{uid} {time_} {pre_time} {price}\n""")  # 注意手动添加换行符
    print(pre, time_, pre_time, price)


if __name__ == '__main__':
    uid = '08011015'
    fg_ = ['2508', '2509', '2510', '2511', '2512', '2601', '2602', '2603', '2604', '2605', '2606', '2607']
    # 郑州 锰硅 # 硅铁  # 纯碱  # 玻璃
    category = ['SM', 'SF', 'SA', 'FG']
    for _pre in category:
        for _time in fg_:
            # zhengzhou
            # get_data_sina(_pre, _time, uid)
            pass

    # 大连 焦煤
    category_b = ['JM']
    for _pre in category_b:
        for _time in fg_:
            # get_data_baidu(_pre, _time, uid)
            pass

    # 广州 多晶硅
    # 上海 螺纹钢
    # category_g = ['ps', 'rb']
    # 沪铜
    category_g = ['cu']
    for _pre in category_g:
        for _time in fg_:
            get_data_easymoney(_pre, _time, uid)
            pass
